package cn.apienvrypt.advice;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import com.google.gson.Gson;

import cn.apienvrypt.context.HandleContext;
import cn.apienvrypt.domain.RequestDto;
import cn.apienvrypt.domain.SignDto;
import cn.apienvrypt.util.AESUtil;
import cn.apienvrypt.util.Base64Util;
import cn.apienvrypt.util.GsonUtil;
import cn.apienvrypt.util.RSAUtil;

/**
 * @author lfj
 */
public class DecryptHttpInputMessage implements HttpInputMessage {

	private Logger log = LoggerFactory.getLogger(this.getClass());
	private HttpHeaders headers;
	private InputStream body;

	public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, String charset, boolean showLog) throws Exception {

		if(StringUtils.isEmpty(privateKey)) {
			throw new IllegalArgumentException("RSA私钥不能为空");
		}

		this.headers = inputMessage.getHeaders();
		String content = new BufferedReader(new InputStreamReader(inputMessage.getBody()))
			.lines()
			.collect(Collectors.joining(System.lineSeparator()));

		String decryptBody = content;
		if(content.startsWith("{")) {
			Gson gson = GsonUtil.getGson();
			RequestDto bodyRequest = gson.fromJson(decryptBody, RequestDto.class);
			String signStr = new String(RSAUtil.decrypt(Base64Util.decode(bodyRequest.getSign()), privateKey), charset);
			SignDto signDto = gson.fromJson(signStr, SignDto.class);
			decryptBody = AESUtil.getInstance()
				.decrypt(signDto.getKey(), bodyRequest.getEc());
			HandleContext.setValue(signDto.getKey());
		}

		this.body = new ByteArrayInputStream(decryptBody.getBytes());
	}

	@Override
	public InputStream getBody() {
		return body;
	}

	@Override
	public HttpHeaders getHeaders() {
		return headers;
	}
}
